//
//  BLEScanViewController.m
//  RuiHeApp
//
//  Created by Jun on 2023/10/10.
//

#import "BLEScanViewController.h"
#import "RHBleScanCell.h"
#import "CBLECenterMnger.h"
#import "RHNavigationController.h"
#import <YYAnimatedImageView.h>
#import <YYImage/YYImage.h>
#import "RHLocalDeviceVC.h"
#import "BLESetWifiInputController.h"
#import "RHDeviceModel.h"
#import "RHNavgationView.h"
#import "RHNetDevInfoModel.h"
#define ScanTimeInterval        3.0
#define SearchOutTime           20




@interface BLEScanViewController ()<UITableViewDelegate,UITableViewDataSource>


@property (nonatomic ,strong) UITableView *tableView;
//我的设备(匹配蓝牙)
@property (nonatomic ,strong) NSMutableArray *myDeviceArr;
//我的设备列表(后台获取)
@property (nonatomic, strong) NSArray *deviceList;

@property (nonatomic ,strong) NSArray *iconArr;

@property (nonatomic, strong) NSTimer *scanTimeOut;

@property (nonatomic, strong) UIImageView *animateImg_1;

@property (nonatomic, strong) UIImageView *animateImg_2;

@property (nonatomic,strong) QMUIButton *searchBtn;

@property (nonatomic,strong) NSMutableArray *scanDevArr;

@property (nonatomic, strong) RHNavgationView *navgationView;

@property (nonatomic, strong) UIView *topView;

@property (nonatomic, strong) MASConstraint *tableTopConstraint;

@property (nonatomic, assign) BOOL userRoleIsChange;//用户角色是否发生变化,如果是当前是普通用户,绑定设备后变成终端用户,某些
@end

@implementation BLEScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    self.navigationItem.title = @"蓝牙查找".rh_localized;
    self.scanDevArr = [NSMutableArray array];
    self.myDeviceArr = [NSMutableArray array];
    [self setupUI];
    [self getDeviceList];
    kWeakSelf;
    [CBLECenterMnger checkAuthState:^(CBManagerState state) {
        if(state == CBManagerStatePoweredOn){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf scanDevice];
            });
            
        }
    }];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self stopScan];
    [self stopSearchAnimation];
    [(RHNavigationController*)self.navigationController setBackgoundClear:NO titleColor:nil];
   
}

-(void)setupUI
{
    [CBLECenterMnger shareMnger];
    ADD_MESSAGE(BLEMSG_CENTER_POWERON,   msgForBLEPowerOn);
    ADD_MESSAGE(BLEMSG_CENTER_NEWPHERAL, msgForNewPheral:);
    ADD_MESSAGE(BLEMSG_PHERAL_CONNECT_RST, msgForPheralConnect);
    ADD_MESSAGE(BLEMSG_PHERAL_DISCONNECT, msgForPheralReConnect:);
//    ADD_MESSAGE(BLEMSG_LOCAL_DEVICE_CHANGE, msgForLocalDeviceChange);//连接蓝牙成功后保存到本地的通知
    kWeakSelf;
    self.navgationView = [[RHNavgationView alloc]initWithController:self];
    self.navgationView.backgroundColor = CMainColorGreen;
    self.navgationView.title = @"蓝牙查找".rh_localized;
    [self.navgationView setButtonTitleColor:UIColor.whiteColor];
    [self.view addSubview:self.navgationView];
    
    UIView *topView = kView;
    [self.view addSubview:topView];
    self.topView = topView;
    [topView setBackgroundColor:CMainColorGreen];
    
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.navgationView.mas_bottom);
        make.left.right.mas_offset(0);
       
    }];
    
    UIView *imgContentView = kView;
    [topView addSubview:imgContentView];
    [imgContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.top.mas_offset(0);
        make.height.offset(kScaleW(220));
    }];
    
    _animateImg_1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ble_search_bg"]];
    _animateImg_1.contentMode = UIViewContentModeScaleAspectFit;
  
    [imgContentView addSubview:_animateImg_1];
    [_animateImg_1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(kScaleW(0));
        make.bottom.mas_offset(-30);
        make.height.equalTo(weakSelf.animateImg_1.mas_width);
        make.centerX.centerY.centerY.mas_offset(0);
    }];
    
    NSMutableArray *imgArr = [NSMutableArray array];
    for (int i = 1; i<=4; i++) {
//        NSString *path = [[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"ble_searching_%d",i] ofType:nil];
        UIImage *img =  [UIImage imageNamed:[NSString stringWithFormat:@"ble_searching_%d",i]];
        [imgArr addObject:img];
    }
    _animateImg_2 = [[UIImageView alloc]init];
    _animateImg_2.contentMode = UIViewContentModeCenter;
    _animateImg_2.animationImages = imgArr;
    _animateImg_2.animationDuration = 2;
    _animateImg_2.animationRepeatCount = CGFLOAT_MAX;
    [imgContentView addSubview:_animateImg_2];
    [_animateImg_2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(weakSelf.animateImg_1);
        make.centerX.centerY.equalTo(weakSelf.animateImg_1);
       
    }];
    
    UIView *titleView = kView;
    titleView.backgroundColor = UIColor.whiteColor;
    titleView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    titleView.layer.cornerRadius = 20;
    [self.view addSubview:titleView];
   
    
    QMUIButton *searchBtn = [[QMUIButton alloc]init];
    [searchBtn setTitle:@"重新查找".rh_localized forState:UIControlStateNormal];
    [searchBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    searchBtn.titleLabel.font = kSYSTEMFONT(16);
    [searchBtn setCornerRadius:8];
    self.searchBtn = searchBtn;
    [searchBtn setBackgroundColor:CMainColorGreen];
    [self.view addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
        make.height.offset(50);
    }];
    [[searchBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        
//        RHLocalDeviceVC *deviceVC = [[RHLocalDeviceVC alloc]init];
//        deviceVC.title = [CBLECenterMnger shareMnger].curPheral.devName;
//        [weakSelf.navigationController pushViewController:deviceVC animated:YES];
//        return;
//        BLESetWifiInputController *deviceVC = [[BLESetWifiInputController alloc]init];
//        [weakSelf.navigationController pushViewController:deviceVC animated:YES];
//        return;
        [weakSelf scanDevice];
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.whiteColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHBleScanCell class] forCellReuseIdentifier:@"RHBleScanCell"];
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }

    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.equalTo(weakSelf.searchBtn.mas_top).offset(-10);
      weakSelf.tableTopConstraint = make.top.equalTo(topView.mas_bottom).offset(0);
    }];

    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.equalTo(weakSelf.tableView.mas_top).offset(20);
        make.height.offset(40);
    }];
    
    
}

#pragma mark ------- 获取我的设备列表
-(void)getDeviceList
{
//    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{
                           @"pageNum":@(1),
                           @"pageSize":@(10000),
                           @"status":@""
    };
    [RHDeviceModel startGetWithCompletionAPIKey:H_deviceList argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            self.deviceList = resultModel.data;
            [self filterMyDevice];
            [self.tableView reloadData];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
         
    }];
}
#pragma mark ------- 搜索到的设备匹配我的设备列表
-(void)filterMyDevice
{
    NSMutableArray *myMtbArr = [NSMutableArray array];
    
    if(self.deviceList.count>0){
        for (int i = 0; i < [[CBLECenterMnger shareMnger].dataPherals totalNums]; i++) {
           CDataPheralInfo *p = [[CBLECenterMnger shareMnger].dataPherals dataWithIndex:i];
            for (RHDeviceModel *devModel in self.deviceList) {
                if([p.devName containsString:devModel.deviceId]){
                    //同步搜索到的蓝牙设备
                    p.deviceId = devModel.deviceId;
                    [myMtbArr addObject:p];
                    
                }
            }
        }
    }
    self.myDeviceArr = myMtbArr;
    
    //搜索到的设备,过滤掉已经存在我的设备列表里的
    NSMutableArray *scanMtbArr = [NSMutableArray array];
    for (int i = 0; i < [[CBLECenterMnger shareMnger].dataPherals totalNums]; i++) {
       CDataPheralInfo *p = [[CBLECenterMnger shareMnger].dataPherals dataWithIndex:i];
        if(self.myDeviceArr.count>0){
            for (CDataPheralInfo *devModel in self.myDeviceArr) {
                if(![p.devName containsString:devModel.devName]){
                    [scanMtbArr addObject:p];
                }
            }
        }else{
            [scanMtbArr addObject:p];
        }
        
    }
    self.scanDevArr = scanMtbArr;
   
}

//读取本地保存的设备
//-(void)readLocalDevices
//{
//    self.localDevArr = [[CDataPheralMnger dataMnger] readBleDevice];
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [self.tableView rectForSection:0];
//    });
//   
//}

//本地保存的蓝牙设备有变化
//-(void)msgForLocalDeviceChange
//{
//    [self readLocalDevices];
//}

- (void)scanDevice{
    if ([CBLECenterMnger BLEIsPowerOff] ) {
        return;
    }
  
    if(![CBLECenterMnger shareMnger].isScaning){
        [[CBLECenterMnger shareMnger].dataPherals removeAll];
      
        [self.tableView reloadData];
        //开始扫描外部蓝牙设备
        [self startScanPeripherals];
        [self.searchBtn setTitle:@"停止查找".rh_localized forState:UIControlStateNormal];
        [self startSearchAnimation];
    }else{
        [self stopScan];
        [self.searchBtn setTitle:@"重新查找".rh_localized forState:UIControlStateNormal];
        [self stopSearchAnimation];
        
    }
   
}

-(void)startSearchAnimation
{
    [_animateImg_1.layer removeAnimationForKey:@"rotationAnimation"];
    CABasicAnimation *rotateAnimate = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotateAnimate.fromValue = @(0);
    rotateAnimate.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    rotateAnimate.duration = 1.5;
    rotateAnimate.cumulative = YES;
    rotateAnimate.repeatCount = MAXFLOAT;
    [_animateImg_1.layer addAnimation:rotateAnimate forKey:@"rotationAnimation"];
    [self.animateImg_2 startAnimating];
    [self beginSearchDevice];
    _tableView.ly_emptyView = nil;
}

-(void)stopSearchAnimation
{
   
    [_animateImg_1.layer removeAnimationForKey:@"rotationAnimation"];
    [self.animateImg_2 stopAnimating];
    self.animateImg_2.image = [UIImage imageNamed:@"ble_searching_4"];
    [self finishSearchDevice];
    if ([[CBLECenterMnger shareMnger].dataPherals totalNums] == 0) {
        _tableView.ly_emptyView = [LYEmptyView emptyViewWithImage:[UIImage imageNamed:@"nodata_icon_1"] titleStr:@"未找到设备".rh_localized detailStr:@"请确认设备已正常开启，并且蓝牙开关已打开".rh_localized];
    }else{
        _tableView.ly_emptyView = nil;
    }
    
}



-(void)finishSearchDevice
{
    kWeakSelf;
    [self.tableTopConstraint uninstall];
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        weakSelf.tableTopConstraint = make.top.equalTo(weakSelf.navgationView.mas_bottom).offset(20);
    }];
    [self.tableView setNeedsLayout];
    [UIView animateWithDuration:0.3 animations:^{
       
        [self.view layoutIfNeeded];
    }completion:^(BOOL finished) {
        self.topView.backgroundColor = UIColor.whiteColor;
        [self.navgationView setButtonTitleColor:UIColor.blackColor];
        self.navgationView.backgroundColor = UIColor.whiteColor;
    }];
    
}

-(void)beginSearchDevice
{
    kWeakSelf;
    [self.tableTopConstraint uninstall];
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        weakSelf.tableTopConstraint = make.top.equalTo(weakSelf.topView.mas_bottom);
    }];
    
   [self.tableView setNeedsLayout];
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    }completion:^(BOOL finished) {
       
    }];
    
    self.navgationView.backgroundColor = CMainColorGreen;
    [self.navgationView setButtonTitleColor:UIColor.whiteColor];
    self.topView.backgroundColor = CMainColorGreen;
}

#pragma mark - 扫描定时器
- (void)startScanPeripherals{

    [self.scanDevArr removeAllObjects];
    [[CBLECenterMnger shareMnger] cmdStartScan];
    _scanTimeOut = [RHCustomTimer scheduledTimerWithTimeInterval:SearchOutTime target:self selector:@selector(scanTimeOutAction) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:_scanTimeOut forMode:NSRunLoopCommonModes];
}

- (void)scanTimeOutAction{

    [self stopScan];
    
    if ([[CBLECenterMnger shareMnger].dataPherals totalNums] == 0) {
//        [QMUITips showInfo:@"没有发现设备".rh_localized];
       
    }else{
        
    }
    [self.tableView endHeaderRefresh];
    [self.tableView reloadData];
    [self.searchBtn setTitle:@"重新查找".rh_localized forState:UIControlStateNormal];
    [self stopSearchAnimation];
    
}



//停止扫描
- (void)stopScan{
 
    [_scanTimeOut invalidate];
    _scanTimeOut = nil;
    [[CBLECenterMnger shareMnger] cmdStopScan];
}


-(void)msgForBLEPowerOn{
    // 关闭状态
    if ([CBLECenterMnger BLEIsPowerOff] ) {
        [self stopScan];
        [self.tableView reloadData];
        [self stopSearchAnimation];
        [self.searchBtn setTitle:@"重新查找".rh_localized forState:UIControlStateNormal];
    } else {
        if (![[CBLECenterMnger shareMnger] isScaning]){
            [self scanDevice];
        }
    }
}

#pragma mark ------- 扫描到设备
-(void)msgForNewPheral:(NSNotification*)no{
    [self filterMyDevice];
   [self.tableView reloadData];
}

#pragma mark ------- 蓝牙连接成功 ------
-(void)msgForPheralConnect{
    //取消所有链接超时等待
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    if (self.recieveMsg == NO) {
        return;
    }
    //蓝牙设备连接上
    if ([[CBLECenterMnger shareMnger] isConnectOK]){
      
        [SVProgressHUD dismiss];
        BLESetWifiInputController *deviceVC = [[BLESetWifiInputController alloc]init];
        [self.navigationController pushViewController:deviceVC animated:YES];
        //保存本地
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[CDataPheralMnger dataMnger] saveBleDevice:[CBLECenterMnger shareMnger].curPheral];
        });
        
    }else{
        [SVProgressHUD dismiss];
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"socket connect failed!"];
    }
}

-(void)msgForPheralReConnect:(NSNotification*)no
{
    CBPeripheral *p = [no object];
//    [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"%@%@",p.name,@"已断开".rh_localized]];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    if(self.myDeviceArr.count == 0){
//        return 1;
//    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    if(self.myDeviceArr.count > 0){
//        if(section == 0){
//            return self.myDeviceArr.count;
//        }else{
//            return self.scanDevArr.count;
//        }
//    }
    if(section == 0){
        return self.myDeviceArr.count;
    }
    
    return self.scanDevArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = kView;
  
    UILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.font = kBOLDSYSTEMFONT(16);
    titleLab.textColor = kColorRGBA(63, 68, 67, 1);
    titleLab.textAlignment = NSTextAlignmentLeft;
    [headView addSubview:titleLab];
    
    UILabel *countLab = [[QMUILabel alloc]init];
    countLab.font = kSYSTEMFONT(14);
    countLab.textColor = kColorRGBA(63, 68, 67, 0.8);
    countLab.textAlignment = NSTextAlignmentLeft;
    [headView addSubview:countLab];
    

    if(section == 0){
        titleLab.text = @"设备列表".rh_localized;
        countLab.text = [NSString stringWithFormat:@"%@:%ld",@"数量".rh_localized,self.myDeviceArr.count];
    }else{
        titleLab.text = @"其他设备".rh_localized;
        countLab.text = [NSString stringWithFormat:@"%@:%ld",@"数量".rh_localized,self.scanDevArr.count];
    }

    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headView).offset(15);
        make.centerY.mas_offset(0);
     }];
    
    [countLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLab.mas_right).offset(15);
        make.centerY.mas_offset(0);
     }];
    
   return headView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHBleScanCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHBleScanCell"];

    if (indexPath.section == 0) {
        if (indexPath.row < self.myDeviceArr.count) {
            CDataPheralInfo *data = self.myDeviceArr[indexPath.row];
            cell.dataInfo = data;
        }
    }
    if (indexPath.section == 1) {
        if (indexPath.row<self.scanDevArr.count) {
            CDataPheralInfo *data = self.scanDevArr[indexPath.row];
            cell.dataInfo = data;
        }
        
    }
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    self.userRoleIsChange = NO;
    if ([CBLECenterMnger BLEIsPowerOff]) {
        [QMUITips showInfo:@"请打开蓝牙!".rh_localized];
        return;
    }
    [[CBLECenterMnger shareMnger]cmdStopScan];
    [self stopSearchAnimation];
    
    if(indexPath.section == 0){
        //连接我的设备,找出搜索到的列表里对应的蓝牙设备
        //终端用户及以上用户才会有我的设备  终端用户已经绑定到自己名下了,不需要检查设备的绑定状态,因为返回的是2,也就是给自己的设备配网
        CDataPheralInfo *myPheral = self.myDeviceArr[indexPath.row];
        for (int i = 0;i<[CBLECenterMnger shareMnger].dataPherals.totalNums;i++) {
            CDataPheralInfo *pheral = [[CBLECenterMnger shareMnger].dataPherals dataWithIndex:i];
            if ([pheral.devName containsString:myPheral.devName]) {
                [[CBLECenterMnger shareMnger] cmdConnect2Pheral:pheral];
                break;
            }
        }
       
    }else{
        //连接搜索到的设备
        //如果是游客账号,判断该设备是否被绑定,已经被绑定的设备不可添加
        if ([PrivateMange share].currentUser.orgType == OrganizationTypeUser) {
            CDataPheralInfo *pheral = self.scanDevArr[indexPath.row];
            [self checkDeviceBindingStauts:pheral];
        }else{
            CDataPheralInfo *pheral = self.scanDevArr[indexPath.row];
            [[CBLECenterMnger shareMnger] cmdConnect2Pheral:pheral];
        }
    }

}


#pragma mark ----- 1.点击确定按钮,检查设备状态
//1.端终以上用户,直接配网
//2.普通用户和终端用户
//  2.1 设备未绑定,在安装工人上,如果是,直接绑定,绑定后再配网;
//  2.2 设备未绑定,在安装工人上面的层级,选择一个安装工人进行绑定,再配网
//  2.3 设备已绑定,绑定在别人手上,终止;  绑定在自己手上,进行配网
-(void)checkDeviceBindingStauts:(CDataPheralInfo*)pheral
{
    NSString *deviceId = ValidNullData(pheral.devName);
    
    NSDictionary *para = @{@"deviceId":deviceId
                           };//@"password":passwordCell.textField.text 去掉
    
    //查询是否有绑定设备,如果没有就先绑定设备后再配网
   
    [QMUITips showLoading:@"获取设备信息...".rh_localized inView:self.view];
    [RHNetDevInfoModel startGetWithCompletionAPIKey:H_deviceBindStatus_V3 argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        if(resultModel.code == 200){
           
            NSMutableDictionary *para = [NSMutableDictionary dictionary];
            RHNetDevInfoModel *model = resultModel.data;
            [para setObject:SafeStr(deviceId) forKey:@"deviceId"];
            [para setObject:SafeStr(deviceId) forKey:@"deviceName"];
            [para setObject:SafeStr(model.deviceTypeCode) forKey:@"deviceType"];
            
            [self bindDeviceWithPara:para defaultOrg:model.ordId pheral:pheral];
//            if (model.direct == 1) {
//                //直接走添加流程
//                [self bindDeviceWithPara:para pheral:pheral];
//            }else if (model.direct == 0){
//                //设备在安装商那里,需要选择一个安装工人进行绑定
//                [self selectInstallerWithUserId:model.userId para:para pheral:pheral];
//            }
        }else{
            //错误码,游客用户-->终止
            if ([PrivateMange share].currentUser.orgType == OrganizationTypeUser&&
                [PrivateMange share].currentUser.brandId != brand_id.integerValue) {
                //1.设备未备案(60014)
                //2.设备在别的支路上,返回设备不存存(60026)  -->普通用户继续配网
                //3.设备已被绑定(60033)                  -->普通用户继续配网
                if (resultModel.code != 60014) {
                    [QMUITips hideAllTips];
                    [[CBLECenterMnger shareMnger] cmdConnect2Pheral:pheral];
                }
            }
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}



#pragma mark --------1.1 绑定设备 ------
-(void)bindDeviceWithPara:(NSMutableDictionary*)para defaultOrg:(NSInteger)orgId pheral:(CDataPheralInfo*)pheral{
    
    [QMUITips showLoading:@"绑定设备...".rh_localized inView:kAppWindow];
    [BaseModel startWithCompletionAPIKey:H_deviceUserBind argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            [QMUITips showSucceed:@"绑定设备成功".rh_localized inView:self.view hideAfterDelay:1];
           //此时用户变为终端用户,重新获取用户信息,重载tabbar
           if([PrivateMange share].currentUser.brandId == [brand_id integerValue]){//如果是游客
               dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                   [QMUITips showLoadingInView:self.view];
                   [[PrivateMange share]getUserInfoSuccess:^(RHUserModel * _Nonnull userModel) {
                       self.userRoleIsChange = YES;
                       [[CBLECenterMnger shareMnger] cmdConnect2Pheral:pheral];

                   }];
               });
           }else{

               [[CBLECenterMnger shareMnger] cmdConnect2Pheral:pheral];
           }
        }

    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

//#pragma mark -------- 1.2更新默认组织 ------
//-(void)updateDefaultOrg:(NSInteger)orgId pheral:(CDataPheralInfo*)pheral
//{
//    [QMUITips showLoadingInView:kAppWindow];
//    [BaseModel startGetWithCompletionAPIKey:H_updateVisitorIntoDefaultOrg argument:@{@"userId":@([PrivateMange share].currentUser.userId),@"ordId":@(orgId)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
//        if (resultModel.code == 200) {
//            [QMUITips showSucceed:@"绑定设备成功".rh_localized inView:self.view hideAfterDelay:1];
//            //此时用户变为终端用户,重新获取用户信息,重载tabbar
//            if([PrivateMange share].currentUser.brandId == [brand_id integerValue]){//如果是游客
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    [QMUITips showLoadingInView:self.view];
//                    [[PrivateMange share]getUserInfoSuccess:^(RHUserModel * _Nonnull userModel) {
//                        self.userRoleIsChange = YES;
//                        [[CBLECenterMnger shareMnger] cmdConnect2Pheral:pheral];
//
//                    }];
//                });
//            }else{
//                
//                [[CBLECenterMnger shareMnger] cmdConnect2Pheral:pheral];
//            }
//        }
//    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
//        
//    }];
//    
//}


-(void)dealloc
{
    [self stopScan];
}

@end
